package com.yu.filter;

import com.alibaba.fastjson.JSON;
import com.yu.pojo.Result;
import com.yu.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化方法");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器拦截了请求");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURL().toString();

        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        response.setContentType("application/json;charset=utf-8");
//        PrintWriter writer = response.getWriter();
        if (token == null || token.isEmpty()) {
            Result result = Result.error("NOT_LOGIN");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result result = Result.error("NOT_LOGIN");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }


    @Override
    public void destroy() {
        System.out.println("销毁方法");
    }
}
